<?php


namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

class BaseRouteServiceProvider extends ServiceProvider
{
    protected string $moduleName;
    protected array $route = []; //仅允许小写
    protected array $routeDirectory = []; //路由目录

    public function map()
    {
        foreach ($this->route as $value) {
            Route::prefix($this->getMapPrefix($value))
                ->middleware($this->getMapMiddleware($value)) //Str::snake(
                ->namespace($this->getMapNamespace($value)) //Modules\Admin\Http\Controllers
                ->as($value == 'web' ? $value : "api.$value.")
                ->group(module_path($this->moduleName, "/Routes/" . ($value == 'user' ? 'api' : Str::lower($value)) . ".php"));
        }
        $this->routeDirectoryMap();
    }

    private function routeDirectoryMap()
    {
        foreach ($this->routeDirectory as $value) {
            foreach (glob(module_path($this->moduleName, "/Routes/$value/*.php")) as $file) {
                Route::prefix($this->getMapPrefix($value))
                    ->middleware($this->getMapMiddleware($value)) //Str::snake(
                    ->namespace($this->getMapNamespace($value)) //Modules\Admin\Http\Controllers
                    ->as($value == 'web' ? $value : "api.$value.")
                    ->group($file);
            };
        }
    }

    private function getMapPrefix($value)
    {
        if ($value == 'web') {
            return '';
        }
        if ($value == 'user') {
            return 'api';
        }
        if ($value == 'api') {
            return 'api';
        }
        return config('api.' . Str::snake($value) . ".api_prefix", 'api/' . implode("/", explode('_', Str::snake($value))));
    }

    private function getMapMiddleware($value)
    {
        if ($value == 'web') {
            return 'web';
        }
        return $value != 'admin' ? 'api' : 'admin_api';
    }

    private function getMapNamespace($value)
    {
        $namespace = "Modules\\$this->moduleName\Http\Controllers";
        if ($value == 'web') {
            return $namespace;
        }
        if ($value == 'user') {
            return $namespace;
        }
        if ($value == 'api') {
            return $namespace;
        }
        return $namespace . '\\' . Str::ucfirst(Str::camel($value));
    }
}
